package cn.offcn.service.impl;

import cn.offcn.entity.*;
import cn.offcn.mapper.BlogMapper;
import cn.offcn.mapper.BtypeMapper;
import cn.offcn.mapper.EvaluateMapper;
import cn.offcn.mapper.UserMapper;
import cn.offcn.service.BlogService;
import cn.offcn.utils.OAResult;
import cn.offcn.utils.PageView;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private BtypeMapper btypeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EvaluateMapper evaluateMapper;
    @Override
    public PageView<Blog> getBlogs(int currentPage, int pageSize) {

        PageHelper.startPage(currentPage,pageSize);
        BlogExample blogExample=new BlogExample();
        List<Blog> blogList=blogMapper.selectByExample(blogExample);
        for (Blog blog : blogList) {
            Btype btype=btypeMapper.selectByPrimaryKey(blog.getTypeFk());
            User user=userMapper.selectByPrimaryKey(blog.getuFk());
            blog.setBtype(btype);
            blog.setUser(user);
        }

        PageInfo<Blog> pageInfo=new PageInfo<>(blogList);
        PageView<Blog> pageView=new PageView<>(currentPage,pageSize);
        pageView.setRecords(pageInfo.getList());
        pageView.setTotalrecords(pageInfo.getTotal());
        return pageView;
    }

    @Override
    public Map getBlogByBid(int bid) {

        //查询博客
        Blog blog= blogMapper.selectByPrimaryKey(bid);
        //查询博主信息
        User user=userMapper.selectByPrimaryKey(blog.getuFk());
        //查询评论
        EvaluateExample evaluateExample=new EvaluateExample();
        EvaluateExample.Criteria criteria = evaluateExample.createCriteria();
        criteria.andBFkEqualTo(bid);
        List<Evaluate> evaluateList = evaluateMapper.selectByExample(evaluateExample);
        Map<String,Object> map=new HashMap<>();
        map.put("blog",blog);
        map.put("user",user);
        map.put("evaluateList",evaluateList);
        return map;
    }

    @Override
    public OAResult deleteBlogById(int bid) {

        //删除评论
        EvaluateExample evaluateExample=new EvaluateExample();
        EvaluateExample.Criteria criteria = evaluateExample.createCriteria();
        criteria.andBFkEqualTo(bid);
        evaluateMapper.deleteByExample(evaluateExample);
        //再删除博客
       int rows= blogMapper.deleteByPrimaryKey(bid);
       if(rows==1){
           return OAResult.ok(200,"删除成功");
       }
        return OAResult.ok(400,"删除失败");
    }
}
